<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 地址管理
 * @author chaituan@126.com
 */
class Address extends CI_Controller {
	
	function __construct(){
		parent::__construct();
		$this->load->model('admin/Address_model');
	}
	
	function lists(){
		if(is_ajax_request()){
			$isdefa = Posts('address');
			$uid = Posts('uid','num');
			$items = $this->Address_model->getItems("uid=".$uid,'','id desc');
			if($items){
				foreach ($items as $val){
					if($val['id'] == $isdefa){
						$val['is_default'] = 1;
					}else{
						$val['is_default'] = 0;
					}
					$val['name'] = $val['names'];
					$val['address'] = $val['province'].$val['city'].$val['county'].$val['address_detail'];
					unset($val['names']);
					$item[] = $val;
				}
			}else{
				$item ="";
			}
			AjaxResult(1, "ok", $item);
		}
	}
	
	function insert(){
		if(is_ajax_request()){
			$get = Posts('info');
			$uid = $get['uid'];
			$count = $this->Address_model->count(array('uid'=>$uid));
			if($count >= 10)AjaxResult(2, '最多添加10个地址');
			$d = 0;
			if($get['is_default']=='true'){
				$d = 1;
			}
			$data = array(
					'names'=>$get['name'],'tel'=>$get['tel'],'address_detail'=>$get['address_detail'],
					'province'=>$get['province'],'city'=>$get['city'],'county'=>$get['county'],'area_code'=>$get['area_code']
			);
			$data['uid'] = $uid;
			$data['addtime'] = time();
			$result = $this->Address_model->add($data);
			if($result){
				if($d){
					$this->load->model('admin/User_model');
					$this->User_model->updates_se(array('address'=>$result),array('id'=>$uid));
				}
				AjaxResult(1,'添加成功');
			}else{
				AjaxResult_error();
			}
		}
	}
	
	function edit(){
		if(is_ajax_request()){
			$get = Posts('info');
			$uid = $get['uid'];
			$id = $get['id'];
			$default = $get['is_default'];
			$data = array(
					'names'=>$get['name'],'tel'=>$get['tel'],'address_detail'=>$get['address_detail'],
					'province'=>$get['province'],'city'=>$get['city'],'county'=>$get['county'],'area_code'=>$get['area_code']
			);
			$result = $this->Address_model->updates($data, array('uid'=>$uid,'id'=>$id));
			if($result){
				$this->load->model('admin/User_model');
				if($default=='true'){
					$address = $id;
					$this->User_model->updates_se(array('address'=>$address),array('id'=>$uid));
				}else{
					$user = $this->User_model->getItem(array('id'=>$uid),'address');
					if(!$user['address']){
						$this->User_model->updates_se(array('address'=>$address),array('id'=>$uid));
					}
				}
				AjaxResult(1, '编辑成功');
			}else{
				AjaxResult_error();
			}
		}
	}
	
	function del(){
		if(is_ajax_request()){
			$id = Posts('id','num');
			$uid = Posts('uid','num');
			$result = $this->Address_model->deletes(array('id'=>$id,'uid'=>$uid));
			if($result){
				AjaxResult(1, '删除成功');
			}else{
				AjaxResult_error('删除失败');
			}
		}
	}
	
}
